<template>
  <transition name="message">
    <div class="notify-container" v-if="show">
      <div class="notify-container-content">
        <i
            :class="'el-icon-' + type"
            :style="{ color: iconColor, marginRight: '6px' }"
        ></i
        >{{ message }}
      </div>
    </div>
  </transition>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
export default {
  name: 'zMessage',
  props: {
    message: String,
    duration: {
      type: Number,
      default: 2000
    },
    type: {
      type: String,
      default: 'success'
    },
    icon: String,
    show: {
      type: Boolean,
      default: false
    }
  },
  setup (props, { emit }) {
    const iconColor = ref('#fff')
    let closeNotifyTask = null
    /**
     * 根据 type 设置 icon
     * @param type
     */
    const setColorByType = (type = props.type) => {
      switch (type) {
        case 'success': {
          iconColor.value = '#67C23A';
          break;
        }
        case 'warning': {
          iconColor.value = '#E6A23C';
          break;
        }
        case 'error': {
          iconColor.value = '#F56C6C';
          break;
        }
        default: {
          iconColor.value = '#909399';
        }
      }
    }
    // 关闭通知
    const onClose = () => {
      if (props.duration <= 0) {
        // 不需要主动关闭
        return
      }
      closeNotifyTask = setTimeout(() => {
        emit('update:show', false)
      }, props.duration);
    }
    onMounted(() => {
      setColorByType()
      onClose()
    })
    onUnmounted(() => clearTimeout(closeNotifyTask))
    return {
      iconColor,
      onClose
    }
  },
};
</script>

<style lang="scss" scoped>
.notify-container {
  position: fixed;
  left: 50%;
  transform: translate(-50%);
  background-color: #fff;
  border-radius: 3px;
  top: 15px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  z-index: 1000;

  .notify-container-content {
    line-height: 1;
    padding: 8px 18px;
    font-size: 12px;
  }
}

.message-enter-active,
.message-leave-active {
  transition: all 0.3s ease;
}

.message-enter,
.message-leave-to {
  opacity: 0;
  top: 0;
}
</style>
